import pymysql,sys

#if len(sys.argv) != 6:
#  print(f'Usage: {sys.argv[0]} ip port user password sql_file')
#  sys.exit(1)

user="{{admin_user}}"
passwd="{{admin_passwd}}"
db_host="{{db_host}}"
db_port={{db_port}}
db_user="{{db_user}}"
db_passwd="{{db_passwd}}"
ip="{{rip}}"
db=""

def db_commit(sql):
  conn=None

  #print('-------0----------') 
  conn= pymysql.connect(host=db_host,port=db_port,user=user,password=passwd,database=db, charset="utf8")
  #print('-------2----------') 

  cur = conn.cursor()
  try:
    cur.execute(sql)
    conn.commit()
  except pymysql.Error as e:
    print('mysql.Error: ',e.args[0],e.args[1])  
    conn.rollback()
  conn.close()


def db_grant():
  db="{{db_name}}"
  sql=f'CREATE DATABASE IF NOT EXISTS {db};'
  db=""
  db_commit(sql)
  sql=f'create user if not exists {db_user}@"{ip}" identified by "{db_passwd}";'
  db_commit(sql)
  db="{{db_name}}"
  sql=f'grant all on {db}.* to {db_user}@"{ip}";'
  db=""
  db_commit(sql)

db_grant()

